package com.com.typhoon.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.com.typhoon.annotations.NeedLogin;
import com.com.typhoon.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shuya | dongfeng.zdf@alibaba-inc.com
 * @description
 * @date 2018/10/19 下午7:51
 * @description
 * @modified by
 * @since V2.0.0
 */
@Slf4j
public class CustomInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        NeedLogin needLogin = handlerMethod.getMethod().getAnnotation(NeedLogin.class);
        if(null == needLogin || !needLogin.value()) {
            log.info("{}没有加注解或者不需登录",handlerMethod.getMethod().getName());
            return true;
        }
        this.putFailResult(response,"需要登录");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }

    private void putFailResult(HttpServletResponse response, String msg) {
        Map<String, Object> results = new HashMap<>();
        results.put("code", "error");
        results.put("msg", msg);
        ResponseUtils.renderJson(response, JSONObject.toJSONString(results, SerializerFeature.WriteMapNullValue));
    }
}
